package com.example.android11_udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.http.conn.util.InetAddressUtils;

import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements View.OnClickListener {

	TextView retMsg;
	EditText sendMsg;
	Button send;
	String rMsg;
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
		
		retMsg = (TextView)findViewById(R.id.retMsg);
		sendMsg = (EditText)findViewById(R.id.sendMsg);
		send = (Button)findViewById(R.id.send);
		send.setOnClickListener(this);
		
				
		
		
	}

	@Override
	public void onClick(View v) {
		start();
		retMsg.setText(rMsg);
	}

	private void start() {
		try {
			InetAddress iaddress = InetAddress.getByName("211.183.3.172");
			DatagramSocket dsocket = new DatagramSocket(3000);
			String sendData = sendMsg.getText().toString();
			byte[] sendBuffer = sendData.getBytes();
			DatagramPacket dpacket = new DatagramPacket(sendBuffer, sendBuffer.length, iaddress,4000);
			dsocket.send(dpacket);
			byte[] rceiveBuffer = new byte[600];
			dpacket = new DatagramPacket(rceiveBuffer, rceiveBuffer.length);
			dsocket.receive(dpacket);
			rMsg = new String(dpacket.getData());
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	

}
